import { Component, OnInit, Inject, ViewChild, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgForm, FormControl } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDatepickerInputEvent} from '@angular/material';
import { Moment } from 'moment';
import * as moment from 'moment';
declare var $: any;
import { Asset} from '../../models/Asset';
import { SelectionModel } from '@angular/cdk/collections';
import {map, tap} from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { DepartmentService } from '../../service/departmentService';
import { Department } from '../../models/Department';
import { UserService } from '../../service/userService';
import { AssetService } from '../../service/assetService';
import { User } from '../../models/User';
import { DepartmentaddComponent } from '../departmentadd/departmentadd';
import { UseraddComponent } from '../useradd/useradd';
import { Deliver } from '../../models/Deliver';
import { DeliverService } from '../../service/deliverService';
import { LoginService } from '../../service/loginService';
import {IActionMapping, ITreeOptions, TreeComponent} from 'angular-tree-component';
import {AssetType} from '../../models/AssetType';
@Component({
  templateUrl: './assessTable.html',
  styleUrls: ['./assessTable.css']
})
export class AssessTableComponent implements OnInit, AfterViewChecked {
  options: ITreeOptions = {};
  nodes: any = [];
  assettypeName: string;
  environment = environment;
  typetree: boolean = false;
  @ViewChild(TreeComponent)
  private tree: TreeComponent;
  assetTypes: AssetType[];
  messages = {
    new_departmentid: '',
    new_userid: '',
    address: '',
  };
  selection: SelectionModel<Asset>;
  asset: Asset;
  deliver: Deliver;
  delivers: any = [];
  Assets: Asset[];
  departments: Department[];
  users: User[];
  departmentid: number;
  Page = 0;
  PageSize = 100000000;
  Total: number;
  dealname: string;
  assetIds: any = [];
  appearSearch: boolean = false;
  start_createDate: any;
  end_createDate: any;
  beginCtrl = new FormControl();
  endCtrl = new FormControl();
  updatedelivers: any;
  chukuid: number;
  havecheck: boolean = false;
  actionMapping: IActionMapping = {
    mouse: {
      click: (tree, node, $event) => {
        this.asset.assetType = node.data.GDZCLB_DM;
        this.assettypeName = node.data.GDZCLBMC;
        this.typetree = false;
      }
    }
  };
  cols = ['select', 'assetCode', 'assetName', 'assetType', 'assetDate'];
  constructor(
    private departmentService: DepartmentService,
    private userService: UserService,
    private assetService: AssetService,
    private deliverService: DeliverService,
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private loginService: LoginService,
    private dialogRef: MatDialogRef<AssessTableComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {asset: any}) {
     this.deliver = data.asset || new Deliver();
     this.updatedelivers = data.asset || false;
     this.chukuid = this.updatedelivers.id;
    if (this.updatedelivers.id !== undefined) {
      this.dealname = this.deliver.deliverUser.realName;
    } else {
      this.dealname = this.loginService.user.username;
    }
     this.deliver.deliverDateShow = new FormControl(moment(this.deliver.deliverDate));
     this.deliver.deliverDate = moment(this.deliver.deliverDate).toDate();
  }
  @ViewChild('assetoutForm')
  assetoutForm: NgForm;
  ngAfterViewChecked() {
    if (this.assetoutForm) {
      this.assetoutForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.assetService.getAssetTypes().subscribe((res) => {
      this.assetTypes = res.res;
      for (let i = 0; i < this.assetTypes.length; i++) {
        this.nodes.push({GDZCLBMC: this.assetTypes[i].GDZCLBMC, GDZCLB_DM: this.assetTypes[i].GDZCLB_DM});
      }
      this.nodes.forEach((node, index) => {
        node.children = this.assetTypes[index].children;
      });
    })
    this.options = {displayField: 'GDZCLBMC', idField: 'GDZCLB_DM', actionMapping: this.actionMapping };
    const initialSelection = [];
    const allowMultiSelect = true;
    this.selection = new SelectionModel<Asset>(allowMultiSelect, initialSelection);
    if (this.updatedelivers.id !== undefined) {
      this.departmentid = Number(this.deliver.sysDepartment.id);
      this.getUsers().subscribe();
    }
      this.getDepartments();
    this.getAssets(this.Page).subscribe(() => {
      this.Assets.forEach((asset) => {
        asset.checked = false;
      })
    });
  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.Assets.length;
    return numSelected === numRows;
  }
  allToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.Assets.forEach(row => {this.selection.select(row); });
  }
  itemChanged(item, event) {
    item.isChecked = event.checked;
    if (item.isChecked) {
      this.assetIds.push(item.id);
      item.checked = true;
      this.havecheck = true;
    } else {
      item.checked = false;
      for (let i = 0; i < this.assetIds.length; i++ ) {
        if (this.assetIds[i] === item.id) {
          this.assetIds.splice(i, 1);
        }
      }
    }
  }

  getAssets(page: number) {
    const options: any = {};
    options.assetStatus = 0;
    options.repairStatus = 4;
    if (this.asset.assetName) {options.assetName = this.asset.assetName; }
    if (this.asset.assetCode) {options.assetCode = this.asset.assetCode; }
    if (this.asset.assetVersion) {options.assetVersion = this.asset.assetVersion; }
    if (this.asset.sourceComefrom) {options.sourceComefrom = this.asset.sourceComefrom; }
    if (this.asset.assetBrand) {options.assetBrand = this.asset.assetBrand; }
    if (this.asset.sysUser.username) {options.assetName = this.asset.sysUser.username; }
    if (this.asset.seatNum) {options.seatNum = this.asset.seatNum; }
    if (this.asset.address) {options.address = this.asset.address; }
    if (this.asset.snNum) {options.snNum = this.asset.snNum; }
    if (this.asset.invoiceNum) {options.invoiceNum = this.asset.invoiceNum; }
    if (this.asset.remark) {options.remark = this.asset.remark; }
    if (this.asset.assetType) {options.assetType = this.asset.assetType; }
    if (this.asset.source) {options.source = this.asset.source; }
    if (this.asset.sysDepartment.id) {options.assetDepartmentId = this.asset.sysDepartment.id; }
    if (this.asset.sysUser.id) {options.assetUserId = this.asset.sysUser.id; }
    if (this.start_createDate) {const start = this.start_createDate.toDate(); options.start_createDate = start; }
    if (this.end_createDate) {const end = this.end_createDate.toDate(); options.end_createDate = end ; }
    if (this.havecheck) {
      this.assetIds.forEach((id) => {
        this.assetService.getAsset(id).subscribe((result) => {
          if (result.success) {
            result.res.checked = true;
          }
        })
      })
    }
    return this.assetService.getAssets(page, this.PageSize, options).pipe(tap((res) => {
      this.Assets = res.res;
      this.Total = res.total;
      this.Page = page;
    }));
  }
  appearSearchbox() {
    this.appearSearch = true;
  }
  bigsearch() {
    this.appearSearch = false;
    this.getAssets(this.Page).subscribe();
  }
  onSwitchDate(_: Moment) {
    this.start_createDate = this.beginCtrl.value;
    this.end_createDate = this.endCtrl.value;
  }
  closesearch() {
    this.appearSearch = false;
  }
  showtypeTree() {
    this.typetree = !this.typetree;
  }
  hidetree() {
    this.typetree = false;
  }
  reset() {
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.assettypeName = '';
    this.beginCtrl = new FormControl();
    this.endCtrl = new FormControl();
    this.start_createDate = false;
    this.end_createDate = false;
  }
  onPageChange(page: number) {
    this.Page = page;
    this.getAssets(page).subscribe();
  }
  onSelectdeliverDate(event: MatDatepickerInputEvent<Moment>) {
    this.deliver.deliverDate = event.value.toDate();
    this.deliver.deliverDateShow = new FormControl(event.value);
  }
  getDepartments() {
    this.departmentService.getAllDepartments().subscribe((res) => {
      this.departments = res.res;
    })
  }
  changeDepartment(departmentId) {
    this.departmentid = departmentId;
    this.getUsers().subscribe();
  }
  getUsers() {
    return this.userService.getUsers(1, 20, this.departmentid).pipe(tap((res) => {
      this.users = res.res;
    }))
  }
  changeUser(userid) {
    this.userService.getUser(userid).subscribe((res) => {
      this.deliver.address = String(res.res.seatNum);
    })
  }
  addDepartment() {
    const dialogRef = this.dialog.open(DepartmentaddComponent, {
      width: '500px',
      height: '300px'
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.getDepartments();
    })
  }
  addPerson() {
    const dialogRef = this.dialog.open(UseraddComponent, {
      width: '500px',
      height: '600px',
      data: {
        departments: this.departments
      }
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.getUsers();
    })
  }

  onSubmit() {
    this.deliver.ids = this.assetIds.join(',');
    this.deliver.type = 1;
    this.deliver.deliverid = Number(this.loginService.user.id);
    this.checkValidate(true);
    if (this.assetoutForm.invalid) {
      // 触发mat的error
      this.assetoutForm.onSubmit(null);
      return false;
    }
    if (this.updatedelivers.id !== undefined) {
      this.updatedelivers.list.forEach((value) => {
        this.delivers.push({id: this.chukuid, new_departmentid: this.deliver.new_departmentid, new_userid: this.deliver.new_userid,
          address: this.deliver.address, seatNum: this.deliver.seatNum, deliverDate: this.deliver.deliverDate, remark: this.deliver.remark, type: this.deliver.type,
          });
      })
      this.deliverService.updatebatch(this.delivers).subscribe((res) => {
        this.dialogRef.close(res);
      });
    } else {
      this.deliverService.create(this.deliver).subscribe((res) => {
        if (res.success) {
          this.dialogRef.close(res.res);
        }
      })
    }
  }
  trackBynewId(index: number, item: any) {
    return item.id;
  }
  checkValidate(isSubmit?: boolean) {
    const form = this.assetoutForm;

    for (const field in AssessTableComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = AssessTableComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }
    }
  }
  static ErrorMessages = {
    new_departmentid: {
      required: '领用后使用部门不能为空'
    },
    new_userid: {
      required: '领用后使用人不能为空'
    },
    address: {
      required: '领用后座位号不能为空'
    },
  };
}
